package com.banciyuan.wallpaper.page;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.banciyuan.wallpaper.R;
import com.banciyuan.wallpaper.api.CoreApi;
import com.banciyuan.wallpaper.base.BaseActivity;
import com.banciyuan.wallpaper.bean.Item;
import com.banciyuan.wallpaper.cache.JsonCache;
import com.banciyuan.wallpaper.page.display.DisplayFragment;
import com.banciyuan.wallpaper.page.display.lazy.BasePageFragment;
import com.banciyuan.wallpaper.page.display.transform.DepthPageTransformer;
import com.banciyuan.wallpaper.page.setting.SettingActivity;
import com.banciyuan.wallpaper.setting.SettingConfig;
import com.banciyuan.wallpaper.toast.MyToast;
import com.banciyuan.wallpaper.util.HttpUtils;
import com.banciyuan.wallpaper.util.JsonStatus;
import com.banciyuan.wallpaper.util.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.pnikosis.materialishprogress.ProgressWheel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class MainActivity extends BaseActivity {

    private List<Item> data = new ArrayList<>();
    private List<Fragment> flist = new ArrayList<>();
    private ViewPager viewPager;
    private ProgressWheel wheel;
    protected final Handler mHandler = new Handler();
    private boolean mClickBack = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        OnInitUI();
        OnNetWork();
    }

    @Override
    protected void OnNetWork() {
        final Gson gson = new Gson();
        if (!NetUtils.isNetworkAvailable(getBaseContext())) {
            readJson(gson);
        } else {
            Map<String, String> map = new HashMap<>();
            map.put("type", SettingConfig.ReadSettingString(getBaseContext(), SettingConfig.SEX));
            CoreApi coreApi = retrofit.create(CoreApi.class);
            coreApi.getList(HttpUtils.getData(map))
                    .subscribeOn(Schedulers.io())
                    .map(new Func1<JsonObject, List<Item>>() {
                        @Override
                        public List<Item> call(JsonObject jsonObject) {
                            if (JsonStatus.getJsonStatus(jsonObject)) {
                                String result = jsonObject.get("data").toString();
                                JsonCache.WriteCacheString(getBaseContext(), JsonCache.COUNT, result);
                                return gson.fromJson(result, new TypeToken<List<Item>>() {
                                }.getType());
                            } else {
                                return null;
                            }
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<Item>>() {
                        @Override
                        public void onCompleted() {
                            initFragment(doFilter(data));
                            wheel.setVisibility(View.GONE);
                        }

                        @Override
                        public void onError(Throwable e) {
                            readJson(gson);
                            wheel.setVisibility(View.GONE);
                        }

                        @Override
                        public void onNext(List<Item> tlist) {
                            data = tlist;
                        }
                    });
        }
    }

    private void readJson(Gson gson){
        String result = JsonCache.ReadCacheString(getBaseContext(), JsonCache.COUNT);
        if (!TextUtils.isEmpty(result)) {
            List<Item> templist = gson.fromJson(result, new TypeToken<List<Item>>() {
            }.getType());
            initFragment(templist);
        } else {
            MyToast.show(this, getString(R.string.net_wrong));
        }
    }

    private List<Item> doFilter(List<Item> tlist) {
        List<Item> templist = new ArrayList<>();
        for (Item t : tlist) {
            if (t.getType().equals("V1")) {
                templist.add(t);
            }
        }
        return templist;
    }

    @Override
    protected void OnInitUI() {
        viewPager = (ViewPager) findViewById(R.id.vp);
        wheel = (ProgressWheel) findViewById(R.id.progress_wheel);
    }

    private void initFragment(List<Item> tlist) {
        for (Item item : tlist) {
            Fragment fragment = new DisplayFragment();
            Bundle bundle = new Bundle();
            bundle.putParcelable("item", item);
            fragment.setArguments(bundle);
            flist.add(fragment);
        }

        viewPager.setAdapter(new MainFragmentPagerAdapter(getSupportFragmentManager()));
        int index = tlist.size() > 5 ? 5 : tlist.size();
        viewPager.setOffscreenPageLimit(index);
        viewPager.setPageTransformer(true, new DepthPageTransformer());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == SettingActivity.SETTING_CHANGE) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

    private class MainFragmentPagerAdapter extends FragmentPagerAdapter {

        public MainFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return flist.size();
        }

        @Override
        public Fragment getItem(int position) {
            return flist.get(position);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return super.instantiateItem(container, position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
            BasePageFragment basePageFragment = (BasePageFragment) flist.get(position);
            basePageFragment.setDataInitiated(false);
        }
    }

    @Override
    public void onBackPressed() {
        if (!mClickBack) {
            MyToast.show(this, getString(R.string.more_click_exit));
            mClickBack = true;
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mClickBack = false;
                }
            }, 2000);
        } else {
            finish();
        }
    }
}
